#include "confighelper.h"
#include <QDebug>

ConfigHelper& ConfigHelper::instance()
{
    static ConfigHelper instance;
    return instance;
}

ConfigHelper::ConfigHelper(QObject* parent): QObject(parent) {}

bool ConfigHelper::initialize(const QString& configPath)
{
    if (!QFile::exists(configPath))
    {
        qCritical() << "Config file not found:" << configPath;
        return false;
    }

    m_currentConfigPath = configPath;
    m_settings.reset(new QSettings(configPath, QSettings::IniFormat));

    // 检查配置是否有效
    if (m_settings->status() != QSettings::NoError)
    {
        qCritical() << "Error loading config file:" << configPath;
        return false;
    }
    initialized = true;
    return true;
}

QVariant ConfigHelper::getValue(const QString& group,
                                const QString& key,
                                const QVariant& defaultValue) const
{
    if (!m_settings)
    {
        qWarning() << "Config not initialized!";
        return defaultValue;
    }

    m_settings->beginGroup(group);
    QVariant value = m_settings->value(key, defaultValue);
    m_settings->endGroup();
    return value;
}

QString ConfigHelper::getString(const QString& group,
                                const QString& key,
                                const QString& defaultValue) const
{
    return getValue(group, key, defaultValue).toString();
}

int ConfigHelper::getInt(const QString& group,
                         const QString& key,
                         int defaultValue) const
{
    return getValue(group, key, defaultValue).toInt();
}

bool ConfigHelper::getBool(const QString& group,
                           const QString& key,
                           bool defaultValue) const
{
    return getValue(group, key, defaultValue).toBool();
}

double ConfigHelper::getDouble(const QString& group,
                               const QString& key,
                               double defaultValue) const
{
    return getValue(group, key, defaultValue).toDouble();
}
